package test;

import java.util.List;

import org.hibernate.HibernateException;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import trip.*;
import dao.*;

public class Route_stopsDAOTest extends Assert {
	
	private Route_stopsDAO rsD = Factory.getInstance().getRoute_stopsDAO();
	private RouteDAO rD = Factory.getInstance().getRouteDAO();
	private StopDAO sD = Factory.getInstance().getStopDAO();
	
	@DataProvider
	public Object[][] routeStopsData() {
		return new Object[][] {
				{1, true},
				{null, false},
		};
	}
	
	@Test(dataProvider = "routeStopsData")
	public void dataTest(Integer number, boolean expected)	{
		Stop st1 = null, st2 = null;
		Route route = null;
		try {
			Integer count = rsD.getAll().size();
			assertNotNull(count);
			route = new Route(1, 10, "x", true);
			st1 = new Stop(1, "x1");
			Route_stops rs = new Route_stops(1, number, route, st1);
			rD.create(route);
			sD.create(st1);
			rsD.create(rs);
			Route_stops tmpRs = rsD.getById(rs.getId());
			assertNotNull(tmpRs);
			assertEquals(tmpRs.getId(), rs.getId());
			assertTrue(tmpRs.getRoute().equals(rs.getRoute()));
			assertTrue(tmpRs.getStop().equals(rs.getStop()));
			st2 = new Stop(1, "x2");
			sD.create(st2);
			rs.setStop(st2);
			rsD.update(rs);
			tmpRs = rsD.getById(rs.getId());
			assertNotNull(tmpRs);
			assertEquals(tmpRs.getId(), rs.getId());
			assertTrue(tmpRs.getRoute().equals(rs.getRoute()));
			assertTrue(tmpRs.getStop().equals(rs.getStop()));
			rD.delete(route);
			sD.delete(st1);
			sD.delete(st2);
			tmpRs = rsD.getById(rs.getId());
			assertNull(tmpRs);
			assertEquals(rsD.getAll().size(), count.intValue());
		} catch (HibernateException ex) {
			assertFalse(expected);
			if (route != null)
				rD.delete(route);
			if (st1 != null)
				sD.delete(st1);
			if (st2 != null)
				sD.delete(st2);
		} 
	}
	
	@Test
	public void getByRouteTest() {
		List<Route_stops> rss = rsD.getAll();
		assertNotNull(rss);
		List<Route> routes = rD.getAll();
		assertNotNull(routes);
		for(Route route : routes) {
			List<Route_stops> rsByR = rsD.getByRoute(route);
			assertNotNull(rsByR);
			if (rsByR.size() != 0) {
				for(Route_stops rs : rsByR) {
					assertTrue(rs.getRoute().equals(route));
				}
			}
			else {
				for(Route_stops rs : rss) {
					assertFalse(rs.getRoute().equals(route));
				}
			}
		}
	}
	
	@Test
	public void getByStopTest() {
		List<Route_stops> rss = rsD.getAll();
		assertNotNull(rss);
		List<Stop> stops = sD.getAll();
		assertNotNull(stops);
		for(Stop stop : stops) {
			List<Route_stops> rsByS = rsD.getByStop(stop);
			assertNotNull(rsByS);
			if (rsByS.size() != 0) {
				for(Route_stops rs : rsByS) {
					assertTrue(rs.getStop().equals(stop));
				}
			}
			else {
				for(Route_stops rs : rss) {
					assertFalse(rs.getStop().equals(stop));
				}
			}
		}
	}
}